package org.will.demo.commands;

import org.reveno.atp.api.commands.CommandContext;
import org.reveno.atp.api.transaction.TransactionContext;
import org.will.cqrs.command.Command;
import org.will.cqrs.command.CommandAction;
import org.will.cqrs.command.ICommand;
import org.will.cqrs.command.ICommandAction;
import org.will.ddd.eventing.IDomainEvent;
import org.will.demo.domain.MQDemo;

/**
 * Created by EdifierWill on 2016/8/10.
 */
public class UpdateMQDemoCommand  extends Command<MQDemo> {
    public final Long _id;
    public final String _ename;
    public final Double _price;
    public final Double _inventory;

    public UpdateMQDemoCommand(Long id,String ename,Double price,Double inventory){
        this._id = id;
        this._ename = ename;
        this._price = price;
        this._inventory = inventory;
        this.setDomainModelClass(MQDemo.class);
    }

    @Override
    public ICommandAction createAction(ICommand cmd) {
        //由于该处为new id 故当前修改不予使用该为使用生成的new id即参数
        return new UpdateMQDemoCommandAction(cmd,this._id);
    }

    public class UpdateMQDemoCommandAction extends CommandAction {

        public UpdateMQDemoCommandAction(ICommand cmd,Long id){
            super(cmd,id);
        }

        public void handler(ICommandAction action, TransactionContext ctx) {
            // TODO business logic here
            UpdateMQDemoCommandAction a = (UpdateMQDemoCommandAction)action;
            MQDemo mqDemo = ctx.repo().get(MQDemo.class, a._id);
            UpdateMQDemoCommand command = ((UpdateMQDemoCommand)a._cmd);
            mqDemo = mqDemo.Update(command._ename,command._price,command._inventory);
            //System.out.println("transactionAction(UpdateMQDemoCommandAction):" + a._id);

            publishEvents(mqDemo,ctx);
            ctx.repo().store(a._id, mqDemo);
        }
    }
}
